import { useCallback, FC, useEffect, useState } from 'react'
import {
  ReactFlow,
  Background,
  Controls,
  MiniMap,
  addEdge,
  useNodesState,
  useEdgesState,
  ControlButton,
  useOnSelectionChange,
  type OnConnect,
  ReactFlowProvider,
  useViewport,
  useReactFlow,
  useStore
} from '@xyflow/react'
import '@xyflow/react/dist/style.css'
import { ReactSortable } from 'react-sortablejs'

import { initialNodes, nodeTypes } from './nodes'
import { initialEdges, edgeTypes } from './edges'
import Tab from './tabs/Tab'
import NodeDet from './nodeDet/NodeDet'

function Flow(props: any) {
  const { children, handChangeposition, onNodesChange, onEdgesChange, onConnect, onSelectionChange } = props

  // you can access the internal state here
  const reactFlowInstance = useReactFlow()
  const { x, y, zoom } = useViewport()
  const actionChangePosiiton = () => {
    handChangeposition({
      x,
      y,
      zoom
    })
  }
  useEffect(() => {
    actionChangePosiiton()
  })

  const styles = {
    width: '100%'
  }
  return (
    <ReactFlow
      style={styles}
      nodes={props.nodes}
      nodeTypes={props.nodeTypes}
      onNodesChange={onNodesChange}
      edges={props.edges}
      edgeTypes={edgeTypes}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      fitView
      onSelectionChange={onSelectionChange}
      onSelectionEnd={(e) => console.log(e)}
    >
      {children}
    </ReactFlow>
  )
}
export default function WorkFlow() {
  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes)
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges)
  const viewObj = {
    x: 0,
    y: 0,
    zoom: 1
  }
  //flow显示组件key映射
  const mapFlowCenterModule: { [key: string]: string } = {
    a: 'position-logger',
    c: 'cNode'
  }
  const [currentKey, serCurrentKey] = useState('')
  const onConnect: OnConnect = useCallback((connection) => setEdges((edges) => addEdge(connection, edges)), [setEdges])
  //获取最新视口信息

  const handchangepositions = (e) => {
    Object.assign(viewObj, e)
    // setViews({
    //   ...e
    // })
  }
  useEffect(() => {
    console.log(nodes, 'nodes变了')
    console.log(edges, 'edges变了')

    // onNodesChange(nodes)
    // console.log(edges, 'edges变了')
  })
  const drop = (event) => {
    // 阻止默认事件
    event.preventDefault()

    console.log(event)
    const {
      nativeEvent: { layerX, layerY }
    } = event
    const newPosition = {
      x: (layerX - viewObj.x) / viewObj.zoom,
      y: (layerY - viewObj.y) / viewObj.zoom
    }
    const currentAddObj = {
      id: currentKey,
      data: {},
      position: newPosition,
      type: mapFlowCenterModule[currentKey] || 'default'
    }
    // setNodes([...nodes, currentAddObj])
    setNodes((node: any) => node.concat(currentAddObj))
  }
  const allowDrop = (event: any) => {
    event.preventDefault()
  }
  const onSelectKey = (e: string) => {
    console.log(e)
    serCurrentKey(e)
  }
  const onSelectionChange = useCallback((e: any) => {
    console.log(e)
    serCurrentKey(e.nodes[0]?.id)
  }, [])
  return (
    <div style={{ display: 'flex', height: '100%', position: 'relative' }}>
      <Tab onSelectKey={onSelectKey}></Tab>
      <div onDrop={(e) => drop(e)} style={{ flex: 1 }} onDragOver={(e) => allowDrop(e)}>
        <ReactFlowProvider>
          <Flow
            handChangeposition={(e) => handchangepositions(e)}
            nodes={nodes}
            nodeTypes={nodeTypes}
            onNodesChange={onNodesChange}
            edges={edges}
            onSelectionChange={onSelectionChange}
            edgeTypes={edgeTypes}
            onEdgesChange={onEdgesChange}
            onConnect={onConnect}
            fitView
            onSelectionEnd={(e) => console.log(e)}
          >
            <Background />
            {/* <MiniMap /> */}
            <Controls>
              <ControlButton onClick={() => alert('Something magical just happened. ✨')}></ControlButton>
            </Controls>
          </Flow>
        </ReactFlowProvider>
      </div>
      <NodeDet currentKey={currentKey}></NodeDet>
    </div>
  )
}
